<?php

declare(strict_types=1);

namespace App\Common\Helpers;

use App\Common\Constants\StorageModeConstants;
use FFMpeg\Coordinate\TimeCode;
use FFMpeg\FFMpeg;
use FFMpeg\FFProbe;
use Mine\Helper\Str;

/**
 * 视频处理
 * composer require php-ffmpeg/php-ffmpeg
 * ALpine安装ffmpeg命令 apk update && apk add ffmpeg
 * Centos安装ffmpeg命令  yum install epel-release yum install ffmpeg
 * 查看所在目录
 * which ffmpeg
 * which ffprobe
 */
class VideoHelper
{

    /**
     * 获取视频封面
     * @param string $videoPath
     * @param int $time
     * @return string
     */
    public function getVideoCover(string $videoPath,int $time = 10): string
    {
        $key = 'ch_get_vide_cover:'.md5($videoPath);
        $redis = redis();

        $url = $redis->get($key);
        if($url){
            return $url;
        }

        $ffmpeg = FFMpeg::create();
        $video = $ffmpeg->open($videoPath);

        $directory = BASE_PATH.'/public/uploadfile/temp';

        if (! is_dir($directory)) {
            @mkdir($directory, 0755, true);
        }

        $cover = $directory. '/' .Str::getUUID().'_frame.jpg';

        $video->frame(TimeCode::fromSeconds($time))
            ->save($cover);
        $url = '';
        if(file_exists($cover)){
            $url = container()->get(CommonUpload::class)->setStorageMode(StorageModeConstants::OSS)->uploadWrite(file_get_contents($cover));
            $url = config('file.storage.oss.domain','').$url;
            $redis->set($key,$url,30 * 86400);
        }
        return $url;
    }

    /**
     * 获取视频时长
     * @param string $videoPath
     * @return int
     */
    public function getVideoDuration(string $videoPath): int
    {
        $ffprobe = FFProbe::create();

        // 获取视频时长（以秒为单位）
        $durationInSeconds = $ffprobe
            ->format($videoPath)
            ->get('duration');
        return (int)BcMath::round((float)$durationInSeconds,0);
    }
}